﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using LitJson;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices.ComTypes;
using MvCameraControl;
using System.ComponentModel;
using InspectionMAC.Config;
using InspectionMAC.Forms;
using System.Threading;

namespace InspectionMAC.Algorithm
{    

    class AlgorithmModule
    {
        [DllImport("user32.dll")]
        public static extern IntPtr GetDC(IntPtr hWnd);
        [DllImport("user32.dll")]
        private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);

        // 导入 C++ DLL 函数
        [DllImport(@"pp.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        public static extern int det_Init(int deviceId, string engine_path);
        [DllImport(@"pp.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern IntPtr det_Infer(byte[] imageData, int width, int height);
        public static void ImageHandle()
        {
            Console.WriteLine("pData: " + MainForm.main_Form.currP_Data.Length + "  nWidth: " + MainForm.main_Form.currWidth + "  nHeight: " + MainForm.main_Form.currHeight);
            IntPtr resultPtr = det_Infer(MainForm.main_Form.currP_Data, MainForm.main_Form.currWidth, MainForm.main_Form.currHeight);
            if (resultPtr != IntPtr.Zero) // 确保结果不为 null
            {
                string result = Marshal.PtrToStringAnsi(resultPtr);
                byte[] rebytes = Encoding.Default.GetBytes(result);
                byte[] bytes = Encoding.Convert(Encoding.UTF8, Encoding.Default, rebytes, 0, rebytes.Length);
                result = Encoding.Default.GetString(bytes, 0, bytes.Length);

                if (result.Length <= 10)
                {
                    Console.WriteLine("接口错误:  " + result);
                    return;
                }


                if (result != string.Empty)
                {

                    Console.WriteLine("消息标识:\n" + result.Substring(0, 10));
                    Console.WriteLine("Det Result:\n" + result.Substring(12));

                    JsonData jsonData = new JsonData();
                    jsonData = JsonMapper.ToObject(result.Substring(12));
                    string deR = JsonMapper.ToJson(jsonData["defectPositionMessageList"]);
                    List<DefectMessage> defectMessages = new List<DefectMessage>();
                    defectMessages = JsonMapper.ToObject<List<DefectMessage>>(deR);

                    for (int i = 0; i < defectMessages.Count; i++)
                    {
                        Console.WriteLine(defectMessages[i].x + "  " + defectMessages[i].y + "  " + "类型: " + defectMessages[i].defectType + "  " + GetDefectType(defectMessages[i].defectType));
                        ////MessageBox.Show(configs[i].text);
                        List<Point> points = new List<Point>();
                        points = GetPoints(defectMessages[i].x, defectMessages[i].y, defectMessages[i].width, defectMessages[i].height).ToList();
                        pointsList.Add(points);
                    }

                    //MainForm.main_Form.pictureBoxes[0].Image = RectPoints(MainForm.main_Form.pictureBoxes[0].Image);
                }
                else
                {
                    Console.WriteLine("结果: " + "$BlisterOK");
                }

            }
            else
            {
                Console.WriteLine("Det processing failed or instance was not created.");
            }
        }
        public static void ImageHandle(string imagePath)
        {
            // 支持的图片格式（不区分大小写）
            var supportedExtensions = new[] {
            ".jpg", ".jpeg",
            ".bmp", ".png",
            ".gif", ".tiff",
            ".ico"};

            Console.WriteLine(File.Exists("pp.dll")); 
            // 读取本地图片
            //string imagePath = "Test\\1.jpg"; // 替换为您的图片路径
            System.Drawing.Bitmap bitmap = new Bitmap(imagePath);

            // 获取图片数据
            Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
            BitmapData bmpData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat);

            int bytesPerPixel = Bitmap.GetPixelFormatSize(bitmap.PixelFormat) / 8;
            byte[] imageData = new byte[bmpData.Stride * bitmap.Height];

            // 拷贝数据
            System.Runtime.InteropServices.Marshal.Copy(bmpData.Scan0, imageData, 0, imageData.Length);
            bitmap.UnlockBits(bmpData);
            Console.WriteLine("imageData.Length:  "+imageData.Length);
            IntPtr resultPtr = det_Infer(imageData, bitmap.Width, bitmap.Height);
            if (resultPtr != IntPtr.Zero) // 确保结果不为 null
            {
                string result = Marshal.PtrToStringAnsi(resultPtr);
                byte[] rebytes = Encoding.Default.GetBytes(result);
                byte[] bytes = Encoding.Convert(Encoding.UTF8, Encoding.Default, rebytes, 0, rebytes.Length);
                result = Encoding.Default.GetString(bytes, 0, bytes.Length);

                if (result.Length <= 10)
                {
                    Console.WriteLine("接口错误:  "+result);
                    return;
                }


                if (result != string.Empty)
                {

                    Console.WriteLine("消息标识:\n" + result.Substring(0, 10));
                    Console.WriteLine("Det Result:\n" + result.Substring(12));

                    JsonData jsonData = new JsonData();
                    jsonData = JsonMapper.ToObject(result.Substring(12));
                    string deR = JsonMapper.ToJson(jsonData["defectPositionMessageList"]);
                    List<DefectMessage> defectMessages = new List<DefectMessage>();
                    defectMessages = JsonMapper.ToObject<List<DefectMessage>>(deR);

                    for (int i = 0; i < defectMessages.Count; i++)
                    {
                        Console.WriteLine(defectMessages[i].x + "  " + defectMessages[i].y+"  "+"类型: "+ defectMessages[i].defectType+"  "+ GetDefectType(defectMessages[i].defectType));
                        ////MessageBox.Show(configs[i].text);
                        List<Point> points = new List<Point>();
                        points = GetPoints(defectMessages[i].x, defectMessages[i].y, defectMessages[i].width, defectMessages[i].height).ToList();
                        pointsList.Add(points);
                    }
                }
                else
                {
                    Console.WriteLine("结果: " + "$BlisterOK");
                }

            }
            else
            {
                Console.WriteLine("Det processing failed or instance was not created.");
            }
   
        }

        //public static void ImageHandleBitmap(string imagePath)
        //{
        //    System.Drawing.Bitmap bitmap = new Bitmap(imagePath);
        //    List<List<Point>> tempDefectPoints = new List<List<Point>>();
        //    Bitmap displayBitmap = null; // 用于存储最终显示图像的变量

        //    try
        //    {
        //        // 准备图像数据
        //        Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
        //        BitmapData bmpData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat);
        //        byte[] imageData = new byte[bmpData.Stride * bitmap.Height];
        //        Marshal.Copy(bmpData.Scan0, imageData, 0, imageData.Length);
        //        bitmap.UnlockBits(bmpData);

        //        EngineInitialize();

        //        // 执行推理
        //        IntPtr resultPtr = det_Infer(imageData, bitmap.Width, bitmap.Height);
        //        if (resultPtr != IntPtr.Zero)
        //        {
        //            // 解析结果
        //            string rawResult = Marshal.PtrToStringAnsi(resultPtr);
        //            string jsonResult = Encoding.UTF8.GetString(
        //                Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(rawResult))
        //            );

        //            if (jsonResult.Length <= 10)
        //            {
        //                Console.WriteLine($"接口错误: {jsonResult}");

        //                // 创建错误信息图像
        //                displayBitmap = new Bitmap(bitmap);
        //                using (Graphics g = Graphics.FromImage(displayBitmap))
        //                {
        //                    g.DrawString("接口错误",
        //                        new Font("Arial", 20),
        //                        Brushes.Red,
        //                        new Point(10, 10));
        //                }
        //                return;
        //            }

        //            try
        //            {
        //                var jsonData = JsonMapper.ToObject(jsonResult.Substring(12));
        //                var defects = JsonMapper.ToObject<List<DefectMessage>>(
        //                    JsonMapper.ToJson(jsonData["defectPositionMessageList"])
        //                );
        //                defects = FilterDefects(defects);
        //                StringBuilder faultBuilder = new StringBuilder();

        //                foreach (var defect in defects)
        //                {
        //                    string faultType = GetDefectType(defect.defectType);
        //                    faultBuilder.Append($"{faultType}(位置:{defect.x},{defect.y});");

        //                    // 保存缺陷点用于绘制
        //                    var points = GetPoints(defect.x, defect.y, defect.width, defect.height).ToList();
        //                    tempDefectPoints.Add(points);

        //                    Console.WriteLine($"{DateTime.Now:HH:mm:ss} 检测到缺陷: {faultType}" +
        //                                     $"位置({defect.x},{defect.y}), 大小({defect.width}x{defect.height})");
        //                }

        //                displayBitmap = RectPoints1(new Bitmap(bitmap), tempDefectPoints);
        //            }
        //            catch (Exception ex)
        //            {
        //                Console.WriteLine($"解析JSON错误: {ex.Message}");

        //                // 创建带有错误信息的图像
        //                displayBitmap = new Bitmap(bitmap);
        //                using (Graphics g = Graphics.FromImage(displayBitmap))
        //                {
        //                    g.DrawString($"解析错误: {ex.Message}",
        //                        new Font("Arial", 12),
        //                        Brushes.Red,
        //                        new Point(10, 10));
        //                }
        //            }
        //        }
        //        else
        //        {
        //            Console.WriteLine("推理失败: 返回空指针");

        //            // 创建错误信息图像
        //            displayBitmap = new Bitmap(bitmap);
        //            using (Graphics g = Graphics.FromImage(displayBitmap))
        //            {
        //                g.DrawString("推理错误",
        //                    new Font("Arial", 20),
        //                    Brushes.Red,
        //                    new Point(10, 10));
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine($"图像处理异常: {ex.Message}");

        //        // 创建异常信息图像
        //        displayBitmap = new Bitmap(bitmap);
        //        using (Graphics g = Graphics.FromImage(displayBitmap))
        //        {
        //            g.DrawString($"处理异常: {ex.Message}",
        //                new Font("Arial", 12),
        //                Brushes.Red,
        //                new Point(10, 10));
        //        }
        //    }
        //    finally
        //    {
        //        if (displayBitmap == null)
        //        {
        //            displayBitmap = new Bitmap(bitmap);
        //        }

        //        if (MacTestForm.algorithm_Form!=null)
        //        {
        //            MacTestForm.algorithm_Form.Invoke((MethodInvoker)delegate
        //            {
        //                var targetBox = MacTestForm.algorithm_Form.pictureBox1;

        //                // 安全更新图像
        //                if (targetBox.Image != null)
        //                {
        //                    var oldImage = targetBox.Image;
        //                    targetBox.Image = null;
        //                    oldImage.Dispose();
        //                }

        //                targetBox.Image = new Bitmap(displayBitmap);
        //                targetBox.Refresh();
        //            });
        //        }

        //        // 释放临时位图资源
        //        displayBitmap.Dispose();

        //    }
        //}
        public static void ImageHandleBitmap(string imagePath)
        {
            if (!File.Exists(imagePath))
            {
                Console.WriteLine($"文件不存在: {imagePath}");
                return;
            }

            System.Drawing.Bitmap bitmap = null;
            List<List<Point>> tempDefectPoints = new List<List<Point>>();
            List<string> defectTypeNames = new List<string>();
            Bitmap displayBitmap = null;

            try
            {
                // 加载位图
                bitmap = new Bitmap(imagePath);

                // 准备图像数据
                Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                BitmapData bmpData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat);
                byte[] imageData = new byte[bmpData.Stride * bitmap.Height];
                Marshal.Copy(bmpData.Scan0, imageData, 0, imageData.Length);
                bitmap.UnlockBits(bmpData);

                EngineInitialize();

                // 执行推理
                IntPtr resultPtr = det_Infer(imageData, bitmap.Width, bitmap.Height);
                if (resultPtr != IntPtr.Zero)
                {
                    try
                    {
                        // 获取字符串长度（以null结尾）
                        int len = 0;
                        while (Marshal.ReadByte(resultPtr, len) != 0) len++;

                        // 复制到字节数组
                        byte[] buffer = new byte[len];
                        Marshal.Copy(resultPtr, buffer, 0, len);

                        // 尝试UTF-8解码
                        string jsonResult = Encoding.UTF8.GetString(buffer);

                        if (jsonResult.Length > 12)
                        {
                            jsonResult = jsonResult.Substring(12);
                        }

                        // 检查是否是有效的JSON
                        if (jsonResult.Length <= 10 || !jsonResult.Contains("{"))
                        {
                            Console.WriteLine($"接口错误: {jsonResult}");

                            // 创建错误信息图像
                            displayBitmap = new Bitmap(bitmap);
                            //using (Graphics g = Graphics.FromImage(displayBitmap))
                            //{
                            //    g.DrawString("接口错误: " + jsonResult,
                            //        new Font("Arial", 12),
                            //        Brushes.Red,
                            //        new Point(10, 10));
                            //}
                            return;
                        }

                        try
                        {
                            var jsonData = JsonMapper.ToObject(jsonResult);
                            var defects = JsonMapper.ToObject<List<DefectMessage>>(
                                JsonMapper.ToJson(jsonData["defectPositionMessageList"])
                            );
                            defects = FilterDefects(defects);
                            StringBuilder faultBuilder = new StringBuilder();

                            foreach (var defect in defects)
                            {
                                string faultType = GetDefectType(defect.defectType);
                                faultBuilder.Append($"{faultType}(位置:{defect.x},{defect.y});");

                                defectTypeNames.Add(faultType);
                                // 保存缺陷点用于绘制
                                var points = GetPoints(defect.x, defect.y, defect.width, defect.height).ToList();
                                tempDefectPoints.Add(points);

                                Console.WriteLine($"{DateTime.Now:HH:mm:ss} 检测到缺陷: {faultType}" +
                                                 $"位置({defect.x},{defect.y}), 大小({defect.width}x{defect.height})");
                            }

                            if (MacTestForm.macTestForm.isDefect)
                            {
                                displayBitmap = RectPoints2(new Bitmap(bitmap), tempDefectPoints, defectTypeNames);
                            }
                            else
                            {
                                displayBitmap = RectPoints1(new Bitmap(bitmap), tempDefectPoints);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"解析JSON错误: {ex.Message}");

                            // 创建带有错误信息的图像
                            displayBitmap = new Bitmap(bitmap);
                            using (Graphics g = Graphics.FromImage(displayBitmap))
                            {
                                g.DrawString($"解析错误: {ex.Message}\n原始数据: {jsonResult}",
                                    new Font("Arial", 10),
                                    Brushes.Red,
                                    new Point(10, 10));
                            }
                        }
                    }
                    catch (DecoderFallbackException ex)
                    {
                        Console.WriteLine($"编码转换异常: {ex.Message}");

                        // 尝试直接获取ANSI字符串
                        try
                        {
                            string rawResult = Marshal.PtrToStringAnsi(resultPtr);
                            Console.WriteLine($"原始返回数据: {rawResult}");

                            // 创建错误图像
                            displayBitmap = new Bitmap(bitmap);
                            using (Graphics g = Graphics.FromImage(displayBitmap))
                            {
                                g.DrawString($"编码错误: {ex.Message}\n原始数据: {rawResult}",
                                    new Font("Arial", 10),
                                    Brushes.Red,
                                    new Point(10, 10));
                            }
                        }
                        catch (Exception innerEx)
                        {
                            Console.WriteLine($"获取原始数据失败: {innerEx.Message}");

                            // 创建错误图像
                            displayBitmap = new Bitmap(bitmap);
                            using (Graphics g = Graphics.FromImage(displayBitmap))
                            {
                                g.DrawString($"编码错误: {ex.Message}",
                                    new Font("Arial", 12),
                                    Brushes.Red,
                                    new Point(10, 10));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"处理推理结果异常: {ex.Message}");

                        // 创建错误图像
                        displayBitmap = new Bitmap(bitmap);
                        using (Graphics g = Graphics.FromImage(displayBitmap))
                        {
                            g.DrawString($"处理异常: {ex.Message}",
                                new Font("Arial", 12),
                                Brushes.Red,
                                new Point(10, 10));
                        }
                    }
                    finally
                    {

                    }
                }
                else
                {
                    Console.WriteLine("推理失败: 返回空指针");

                    // 创建错误信息图像
                    displayBitmap = new Bitmap(bitmap);
                    using (Graphics g = Graphics.FromImage(displayBitmap))
                    {
                        g.DrawString("推理错误: 返回空指针",
                            new Font("Arial", 12),
                            Brushes.Red,
                            new Point(10, 10));
                    }
                }
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine($"图像文件未找到: {ex.Message}");

                // 创建错误图像
                displayBitmap = new Bitmap(100, 100);
                using (Graphics g = Graphics.FromImage(displayBitmap))
                {
                    g.Clear(Color.White);
                    g.DrawString($"文件未找到: {Path.GetFileName(imagePath)}",
                        new Font("Arial", 10),
                        Brushes.Red,
                        new Point(10, 10));
                }
            }
            catch (OutOfMemoryException ex)
            {
                Console.WriteLine($"内存不足: {ex.Message}");

                // 创建错误图像
                displayBitmap = new Bitmap(100, 100);
                using (Graphics g = Graphics.FromImage(displayBitmap))
                {
                    g.Clear(Color.White);
                    g.DrawString($"内存不足: {ex.Message}",
                        new Font("Arial", 10),
                        Brushes.Red,
                        new Point(10, 10));
                }
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine($"参数错误: {ex.Message}");

                // 创建错误图像
                displayBitmap = new Bitmap(100, 100);
                using (Graphics g = Graphics.FromImage(displayBitmap))
                {
                    g.Clear(Color.White);
                    g.DrawString($"参数错误: {ex.Message}",
                        new Font("Arial", 10),
                        Brushes.Red,
                        new Point(10, 10));
                }
            }
            catch (ExternalException ex) // GDI+异常
            {
                Console.WriteLine($"GDI+错误: {ex.Message}");

                // 创建错误图像
                displayBitmap = new Bitmap(100, 100);
                using (Graphics g = Graphics.FromImage(displayBitmap))
                {
                    g.Clear(Color.White);
                    g.DrawString($"图像处理错误: {ex.Message}",
                        new Font("Arial", 10),
                        Brushes.Red,
                        new Point(10, 10));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"图像处理异常: {ex.Message}");

                // 创建异常信息图像
                displayBitmap = new Bitmap(100, 100);
                using (Graphics g = Graphics.FromImage(displayBitmap))
                {
                    g.Clear(Color.White);
                    g.DrawString($"处理异常: {ex.Message}",
                        new Font("Arial", 10),
                        Brushes.Red,
                        new Point(10, 10));
                }
            }
            finally
            {
                // 确保位图被释放
                if (bitmap != null)
                {
                    bitmap.Dispose();
                    bitmap = null;
                }

                // 确保有图像显示
                if (displayBitmap == null)
                {
                    displayBitmap = new Bitmap(100, 100);
                    using (Graphics g = Graphics.FromImage(displayBitmap))
                    {
                        g.Clear(Color.White);
                        g.DrawString("无图像数据",
                            new Font("Arial", 10),
                            Brushes.Red,
                            new Point(10, 10));
                    }
                }

                // 在UI线程更新图像
                if (MacTestForm.algorithm_Form != null)
                {
                    try
                    {
                        MacTestForm.algorithm_Form.Invoke((MethodInvoker)delegate
                        {
                            var targetBox = MacTestForm.algorithm_Form.pictureBox1;

                            // 安全更新图像
                            if (targetBox.Image != null)
                            {
                                var oldImage = targetBox.Image;
                                targetBox.Image = null;
                                oldImage.Dispose();
                            }

                            targetBox.Image = new Bitmap(displayBitmap);
                            targetBox.Refresh();
                        });
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"更新UI异常: {ex.Message}");
                    }
                }

                // 释放临时位图资源
                if (displayBitmap != null)
                {
                    displayBitmap.Dispose();
                    displayBitmap = null;
                }
            }
        }

        // 辅助方法：检查字符串是否包含可打印字符
        private static bool HasPrintableCharacters(string str)
        {
            if (string.IsNullOrEmpty(str))
                return false;

            foreach (char c in str)
            {
                if (!char.IsControl(c) && c != ' ' && c != '\0')
                    return true;
            }
            return false;
        }

        // 辅助方法：验证JSON格式
        private static bool IsValidJson(string str)
        {
            if (string.IsNullOrWhiteSpace(str))
                return false;

            str = str.Trim();
            return (str.StartsWith("{") && str.EndsWith("}")) ||
                   (str.StartsWith("[") && str.EndsWith("]"));
        }

        // 辅助方法：获取字符串的可打印版本
        private static string GetPrintableString(string str)
        {
            if (string.IsNullOrEmpty(str))
                return "[空字符串]";

            StringBuilder sb = new StringBuilder();
            foreach (char c in str)
            {
                if (char.IsControl(c) && c != '\n' && c != '\r' && c != '\t')
                {
                    sb.Append($"[0x{((int)c):X2}]");
                }
                else
                {
                    sb.Append(c);
                }
            }
            return sb.ToString();
        }

        public static void ImageHandleBitmap1(string imagePath)
        {
            System.Drawing.Bitmap bitmap = new Bitmap(imagePath);
            List<List<Point>> tempDefectPoints = new List<List<Point>>();
            List<string> defectTypeNames = new List<string>(); // 新增：存储缺陷类型名称
            Bitmap displayBitmap = null; // 用于存储最终显示图像的变量

            try
            {
                // 准备图像数据
                Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                BitmapData bmpData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat);
                byte[] imageData = new byte[bmpData.Stride * bitmap.Height];
                Marshal.Copy(bmpData.Scan0, imageData, 0, imageData.Length);
                bitmap.UnlockBits(bmpData);

                EngineInitialize();

                // 执行推理
                IntPtr resultPtr = det_Infer(imageData, bitmap.Width, bitmap.Height);
                if (resultPtr != IntPtr.Zero)
                {
                    // 解析结果
                    string rawResult = Marshal.PtrToStringAnsi(resultPtr);
                    string jsonResult = Encoding.UTF8.GetString(
                        Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(rawResult))
                    );

                    if (jsonResult.Length <= 10)
                    {
                        Console.WriteLine($"接口错误: {jsonResult}");

                        // 创建错误信息图像
                        displayBitmap = new Bitmap(bitmap);
                        //using (Graphics g = Graphics.FromImage(displayBitmap))
                        //{
                        //    g.DrawString("接口错误",
                        //        new Font("Arial", 20),
                        //        Brushes.Red,
                        //        new Point(10, 10));
                        //}
                        return;
                    }

                    try
                    {
                        var jsonData = JsonMapper.ToObject(jsonResult.Substring(12));
                        var defects = JsonMapper.ToObject<List<DefectMessage>>(
                            JsonMapper.ToJson(jsonData["defectPositionMessageList"])
                        );
                        defects = FilterDefects(defects);
                        StringBuilder faultBuilder = new StringBuilder();

                        foreach (var defect in defects)
                        {
                            string faultType = GetDefectType(defect.defectType);
                            faultBuilder.Append($"{faultType}(位置:{defect.x},{defect.y});");

                            defectTypeNames.Add(faultType);
                            // 保存缺陷点用于绘制
                            var points = GetPoints(defect.x, defect.y, defect.width, defect.height).ToList();
                            tempDefectPoints.Add(points);

                            //Console.WriteLine($"{DateTime.Now:HH:mm:ss} 检测到缺陷: {faultType}" +
                            //                 $"位置({defect.x},{defect.y}), 大小({defect.width}x{defect.height})");
                        }

                        if (MacTestForm.macTestForm.isDefect)
                        {
                            displayBitmap = RectPoints2(new Bitmap(bitmap), tempDefectPoints,defectTypeNames);
                        }
                        else
                        {
                            displayBitmap = RectPoints1(new Bitmap(bitmap), tempDefectPoints);
                        }     
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"解析JSON错误: {ex.Message}");

                        // 创建带有错误信息的图像
                        displayBitmap = new Bitmap(bitmap);
                        using (Graphics g = Graphics.FromImage(displayBitmap))
                        {
                            g.DrawString($"解析错误: {ex.Message}",
                                new Font("Arial", 12),
                                Brushes.Red,
                                new Point(10, 10));
                        }
                    }
                }
                else
                {
                    Console.WriteLine("推理失败: 返回空指针");

                    // 创建错误信息图像
                    displayBitmap = new Bitmap(bitmap);
                    using (Graphics g = Graphics.FromImage(displayBitmap))
                    {
                        g.DrawString("推理错误",
                            new Font("Arial", 20),
                            Brushes.Red,
                            new Point(10, 10));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"图像处理异常: {ex.Message}");

                // 创建异常信息图像
                displayBitmap = new Bitmap(bitmap);
                using (Graphics g = Graphics.FromImage(displayBitmap))
                {
                    g.DrawString($"处理异常: {ex.Message}",
                        new Font("Arial", 12),
                        Brushes.Red,
                        new Point(10, 10));
                }
            }
            finally
            {
                if (displayBitmap == null)
                {
                    displayBitmap = new Bitmap(bitmap);
                }

                // 释放临时位图资源
                displayBitmap.Dispose();

            }
        }
        public static void ImageHandleBitmap2(Bitmap bitmap, int index)
        {
            List<string> defectTypeNames = new List<string>();
            List<List<Point>> tempDefectPoints = new List<List<Point>>();
            Bitmap displayBitmap = null; // 用于存储最终显示图像的变量

            try
            {
                // 准备图像数据
                Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                BitmapData bmpData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat);
                byte[] imageData = new byte[bmpData.Stride * bitmap.Height];
                Marshal.Copy(bmpData.Scan0, imageData, 0, imageData.Length);
                bitmap.UnlockBits(bmpData);

                EngineInitialize();

                // 执行推理
                IntPtr resultPtr = det_Infer(imageData, bitmap.Width, bitmap.Height);
                if (resultPtr != IntPtr.Zero)
                {
                    // 解析结果
                    string rawResult = Marshal.PtrToStringAnsi(resultPtr);
                    string jsonResult = Encoding.UTF8.GetString(
                        Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(rawResult))
                    );

                    if (jsonResult.Length <= 10)
                    {
                        Console.WriteLine($"接口错误: {jsonResult}");

                        // 创建错误信息图像
                        displayBitmap = new Bitmap(bitmap);
                        //using (Graphics g = Graphics.FromImage(displayBitmap))
                        //{
                        //    g.DrawString("接口错误",
                        //        new Font("Arial", 20),
                        //        Brushes.Red,
                        //        new Point(10, 10));
                        //}
                        return;
                    }

                    try
                    {
                        var jsonData = JsonMapper.ToObject(jsonResult.Substring(12));
                        var defects = JsonMapper.ToObject<List<DefectMessage>>(
                            JsonMapper.ToJson(jsonData["defectPositionMessageList"])
                        );
                        //defects = FilterDefects(defects);
                        StringBuilder faultBuilder = new StringBuilder();

                        foreach (var defect in defects)
                        {
                            string faultType = GetDefectType(defect.defectType);
                            faultBuilder.Append($"{faultType}(位置:{defect.x},{defect.y});");

                            defectTypeNames.Add(faultType);
                            // 保存缺陷点用于绘制
                            var points = GetPoints(defect.x, defect.y, defect.width, defect.height).ToList();
                            tempDefectPoints.Add(points);

                            Console.WriteLine($"{DateTime.Now:HH:mm:ss} 检测到缺陷: {faultType}" +
                                             $"位置({defect.x},{defect.y}), 大小({defect.width}x{defect.height})");
                        }

                        if (MacTestForm.macTestForm.isDefect)
                        {
                            displayBitmap = RectPoints2(new Bitmap(bitmap), tempDefectPoints, defectTypeNames);
                        }
                        else
                        {
                            displayBitmap = RectPoints1(new Bitmap(bitmap), tempDefectPoints);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"解析JSON错误: {ex.Message}");

                        // 创建带有错误信息的图像
                        displayBitmap = new Bitmap(bitmap);
                        using (Graphics g = Graphics.FromImage(displayBitmap))
                        {
                            g.DrawString($"解析错误: {ex.Message}",
                                new Font("Arial", 12),
                                Brushes.Red,
                                new Point(10, 10));
                        }
                    }
                }
                else
                {
                    Console.WriteLine("推理失败: 返回空指针");

                    // 创建错误信息图像
                    displayBitmap = new Bitmap(bitmap);
                    using (Graphics g = Graphics.FromImage(displayBitmap))
                    {
                        g.DrawString("推理错误",
                            new Font("Arial", 20),
                            Brushes.Red,
                            new Point(10, 10));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"图像处理异常: {ex.Message}");

                // 创建异常信息图像
                displayBitmap = new Bitmap(bitmap);
                using (Graphics g = Graphics.FromImage(displayBitmap))
                {
                    g.DrawString($"处理异常: {ex.Message}",
                        new Font("Arial", 12),
                        Brushes.Red,
                        new Point(10, 10));
                }
            }
            finally
            {
                if (displayBitmap == null)
                {
                    displayBitmap = new Bitmap(bitmap);
                }

                EnqueueDisplayImage(displayBitmap.Clone() as Bitmap, index);



                // 释放临时位图资源
                displayBitmap.Dispose();


            }
        }
        public struct ImageProcessTask<T> where T : struct, ICameraResult
        {
            public Bitmap Bitmap;
            public string SampleId;
            public int StationId;
            public T Result;
            public ManualResetEventSlim CompletionEvent;
        }

        private static readonly object _queueLock = new object();
        private static readonly Queue<object> _taskQueue = new Queue<object>();
        private static bool _isProcessing = false;

        public static void EnqueueImageProcess<T>(Bitmap bitmap, string sampleId, int stationId, ref T result) where T : struct, ICameraResult
        {
            var task = new ImageProcessTask<T>
            {
                Bitmap = bitmap,
                SampleId = sampleId,
                StationId = stationId,
                Result = result,
                CompletionEvent = new ManualResetEventSlim(false)
            };

            lock (_queueLock)
            {
                _taskQueue.Enqueue(task);
                if (!_isProcessing)
                {
                    _isProcessing = true;
                    ThreadPool.QueueUserWorkItem(ProcessTaskQueue);
                }
            }

            task.CompletionEvent.Wait();
            result = task.Result;
            task.CompletionEvent.Dispose();
        }

        private static void ProcessTaskQueue(object state)
        {
            while (true)
            {
                object taskObj;
                lock (_queueLock)
                {
                    if (_taskQueue.Count == 0)
                    {
                        _isProcessing = false;
                        return;
                    }
                    taskObj = _taskQueue.Dequeue();
                }

                // 使用动态类型处理泛型任务
                if (taskObj is ImageProcessTask<CameraResult01> task1)
                {
                    ProcessImageCore(task1.Bitmap, task1.SampleId, task1.StationId, ref task1.Result);
                    task1.CompletionEvent.Set();
                }
                else if (taskObj is ImageProcessTask<CameraResult02> task2)
                {
                    ProcessImageCore(task2.Bitmap, task2.SampleId, task2.StationId, ref task2.Result);
                    task2.CompletionEvent.Set();
                }
                else if (taskObj is ImageProcessTask<CameraResult03> task3)
                {
                    ProcessImageCore(task3.Bitmap, task3.SampleId, task3.StationId, ref task3.Result);
                    task3.CompletionEvent.Set();
                }
            }
        }
        private static void ProcessImageCore<T>(Bitmap bitmap, string sampleId, int stationId, ref T result) where T : struct, ICameraResult
        {
            List<List<Point>> tempDefectPoints = new List<List<Point>>();
            List<string> defectTypeNames = new List<string>(); // 新增：存储缺陷类型名称
            Bitmap displayBitmap = null;

            try
            {
                // 准备图像数据
                Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                BitmapData bmpData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat);
                int bytesPerPixel = Bitmap.GetPixelFormatSize(bitmap.PixelFormat) / 8;
                byte[] imageData = new byte[bmpData.Stride * bitmap.Height];
                Marshal.Copy(bmpData.Scan0, imageData, 0, imageData.Length);
                bitmap.UnlockBits(bmpData);

                EngineInitialize();

                // 执行推理
                IntPtr resultPtr = det_Infer(imageData, bitmap.Width, bitmap.Height);
                if (resultPtr != IntPtr.Zero)
                {
                    // 获取结果并处理编码
                    string rawResult = Marshal.PtrToStringAnsi(resultPtr);
                    byte[] rebytes = Encoding.Default.GetBytes(rawResult);
                    byte[] bytes = Encoding.Convert(Encoding.UTF8, Encoding.Default, rebytes);
                    string convertedResult = Encoding.Default.GetString(bytes);

                    // 检查结果长度
                    if (convertedResult.Length <= 10)
                    {
                        result.isNG = false;
                        //Console.WriteLine("接口错误: " + convertedResult);
                        //result.Faults = "接口错误";
                        //displayBitmap = CreateErrorBitmap(bitmap, "接口错误");
                        return;
                    }
                    // 提取消息标识和JSON内容
                    string messageId = convertedResult.Substring(0, 10);
                    string jsonContent = convertedResult.Substring(12);

                    //Console.WriteLine("消息标识:\n" + messageId);
                    //Console.WriteLine("Det Result:\n" + jsonContent);

                    try
                    {
                        // 解析JSON
                        JsonData jsonData = JsonMapper.ToObject(jsonContent);
                        string deR = JsonMapper.ToJson(jsonData["defectPositionMessageList"]);
                        List<DefectMessage> defectMessages = JsonMapper.ToObject<List<DefectMessage>>(deR);


                        defectMessages = FilterDefects(defectMessages);
                        // 处理缺陷结果
                        if (defectMessages.Count > 0)
                        {
                            result.isNG = true;
                            StringBuilder faultBuilder = new StringBuilder();

                            foreach (var defect in defectMessages)
                            {
                                string defectTypeName = GetDefectType(defect.defectType);
                                faultBuilder.Append($"{defectTypeName}(位置:{defect.x},{defect.y});");
                                defectTypeNames.Add(defectTypeName);
                                Console.WriteLine($"{defect.x}  {defect.y}  类型: {defect.defectType}  {defectTypeName}");

                                // 保存缺陷点用于绘制
                                List<Point> points = GetPoints(defect.x, defect.y, defect.width, defect.height).ToList();
                                tempDefectPoints.Add(points);
                            }

                            result.Faults = faultBuilder.ToString();
                        }
                        else
                        {
                            result.isNG = false;
                            result.Faults = "OK";
                            Console.WriteLine("结果: $BlisterOK");
                        }

                        // 绘制缺陷框
                        if (tempDefectPoints.Count > 0)
                        {
                            if (MacTestForm.macTestForm.isDefect)
                            {
                                displayBitmap = RectPoints2(new Bitmap(bitmap), tempDefectPoints, defectTypeNames);
                            }
                            else
                            {
                                displayBitmap = RectPoints1(new Bitmap(bitmap), tempDefectPoints);
                            }
                        }
                        else
                        {
                            displayBitmap = new Bitmap(bitmap);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"解析JSON错误: {ex.Message}\n{ex.StackTrace}");
                        result.Faults = "解析错误";
                        displayBitmap = CreateErrorBitmap(bitmap, $"解析错误: {ex.Message}");
                    }
                }
                else
                {
                    Console.WriteLine("推理失败: 返回空指针");
                    result.Faults = "推理错误";
                    displayBitmap = CreateErrorBitmap(bitmap, "推理错误");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"图像处理异常: {ex.Message}\n{ex.StackTrace}");
                result.Faults = $"处理异常: {ex.Message}";
                displayBitmap = CreateErrorBitmap(bitmap, $"处理异常: {ex.Message}");
            }
            finally
            {
                if (displayBitmap != null)
                {
                    EnqueueDisplayImage(displayBitmap.Clone() as Bitmap, stationId);
                }
                


                try
                {
                    string productId = ProductInfoManager.CurrentProductId;
                    string productName = ProductInfoManager.CurrentProductName;
                    switch (stationId)
                    {
                        case 1:
                            CameraResult01 cameraResult1 = new CameraResult01();
                            cameraResult1.DataTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                            cameraResult1.Location = "工位1位置";
                            cameraResult1.iWidth = bitmap.Width.ToString();
                            cameraResult1.iHeight = bitmap.Height.ToString();
                            cameraResult1.iName = "工位一";
                            cameraResult1.isOkSave = true;
                            cameraResult1.Faults = result.Faults;
                            cameraResult1.isNG = result.isNG;
                            BuilderManager.UpdateBuilderForCamera1(productId, productName, sampleId, cameraResult1);
                            if (cameraResult1.isNG)
                            {
                                SingleItemInfoBuilder.Camera1NGCounts += 1;
                            }
                            else
                            {
                                SingleItemInfoBuilder.Camera1OKCounts += 1;
                            }
                            break;
                        case 2:
                            CameraResult02 cameraResult2 = new CameraResult02();
                            cameraResult2.DataTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                            cameraResult2.Location = "工位2位置";
                            cameraResult2.iWidth = bitmap.Width.ToString();
                            cameraResult2.iHeight = bitmap.Height.ToString();
                            cameraResult2.iName = "工位二";
                            cameraResult2.isOkSave = true;
                            cameraResult2.Faults = result.Faults;
                            cameraResult2.isNG = result.isNG;
                            BuilderManager.UpdateBuilderForCamera2(productId, productName, sampleId, cameraResult2);
                            if (cameraResult2.isNG)
                            {
                                SingleItemInfoBuilder.Camera2NGCounts += 1;
                            }
                            else
                            {
                                SingleItemInfoBuilder.Camera2OKCounts += 1;
                            }
                            break;
                        case 3:
                            CameraResult03 cameraResult3 = new CameraResult03();
                            cameraResult3.DataTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                            cameraResult3.Location = "工位3位置";
                            cameraResult3.iWidth = bitmap.Width.ToString();
                            cameraResult3.iHeight = bitmap.Height.ToString();
                            cameraResult3.iName = "工位三";
                            cameraResult3.isOkSave = true;
                            cameraResult3.Faults = result.Faults;
                            cameraResult3.isNG = result.isNG;
                            BuilderManager.UpdateBuilderForCamera3(productId, productName, sampleId, cameraResult3);
                            if (cameraResult3.isNG)
                            {
                                SingleItemInfoBuilder.Camera3NGCounts += 1;
                            }
                            else
                            {
                                SingleItemInfoBuilder.Camera3OKCounts += 1;
                            }
                            break;

                    }
                }
                catch
                {
                    Console.WriteLine("存储失败");
                }
                // 释放资源
                if (displayBitmap != null)
                {
                    displayBitmap.Dispose();
                }
            }
        }
        private static bool isEngineInitialized = false;
        private static readonly object initLock = new object();

        private static void EngineInitialize()
        {
            // 双重检查锁确保线程安全
            if (!isEngineInitialized)
            {
                lock (initLock)
                {
                    if (!isEngineInitialized)
                    {
                        // 初始化检测引擎
                        int deviceId = 0;
                        string enginePath = CurrentEngine;
                        int result = det_Init(deviceId, enginePath);

                        if (result != 0)
                        {
                            MacTestForm.macTestForm.AddLog("检测引擎初始化失败");
                            // 允许后续调用再次尝试初始化
                        }
                        else
                        {
                            MacTestForm.macTestForm.AddLog("检测引擎初始化成功");
                            isEngineInitialized = true; // 仅成功时标记为已初始化
                        }
                    }
                }
            }
        }
        private static void EnqueueDisplayImage(Bitmap image, int stationId)
        {
            switch (stationId)
            {
                case 1:
                    MacTestForm.DisplayQueue01.Enqueue(image);
                    break;
                case 2:
                    MacTestForm.DisplayQueue02.Enqueue(image);
                    break;
                case 3:
                    MacTestForm.DisplayQueue03.Enqueue(image);
                    break;
            }
        }
        public static void ProcessImage1<T>(string imagePath, string sampleId, int stationId, ref T result) where T : struct, ICameraResult
        {
            System.Drawing.Bitmap bitmap = new Bitmap(imagePath);
            List<List<Point>> tempDefectPoints = new List<List<Point>>();
            Bitmap displayBitmap = null;

            try
            {
                // 准备图像数据
                Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                BitmapData bmpData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat);
                int bytesPerPixel = Bitmap.GetPixelFormatSize(bitmap.PixelFormat) / 8;
                byte[] imageData = new byte[bmpData.Stride * bitmap.Height];
                Marshal.Copy(bmpData.Scan0, imageData, 0, imageData.Length);
                bitmap.UnlockBits(bmpData);

                EngineInitialize();

                // 执行推理
                IntPtr resultPtr = det_Infer(imageData, bitmap.Width, bitmap.Height);
                if (resultPtr != IntPtr.Zero)
                {
                    // 获取结果并处理编码
                    string rawResult = Marshal.PtrToStringAnsi(resultPtr);
                    byte[] rebytes = Encoding.Default.GetBytes(rawResult);
                    byte[] bytes = Encoding.Convert(Encoding.UTF8, Encoding.Default, rebytes);
                    string convertedResult = Encoding.Default.GetString(bytes);

                    // 检查结果长度
                    if (convertedResult.Length <= 10)
                    {
                        Console.WriteLine("接口错误: " + convertedResult);
                        result.Faults = "接口错误";
                        //displayBitmap = CreateErrorBitmap(bitmap, "接口错误");
                        return;
                    }

                    // 提取消息标识和JSON内容
                    string messageId = convertedResult.Substring(0, 10);
                    string jsonContent = convertedResult.Substring(12);

                    Console.WriteLine("消息标识:\n" + messageId);
                    Console.WriteLine("Det Result:\n" + jsonContent);

                    try
                    {
                        // 解析JSON
                        JsonData jsonData = JsonMapper.ToObject(jsonContent);
                        string deR = JsonMapper.ToJson(jsonData["defectPositionMessageList"]);
                        List<DefectMessage> defectMessages = JsonMapper.ToObject<List<DefectMessage>>(deR);

                        // 处理缺陷结果
                        if (defectMessages.Count > 0)
                        {
                            result.isNG = true;
                            StringBuilder faultBuilder = new StringBuilder();

                            foreach (var defect in defectMessages)
                            {
                                string defectTypeName = GetDefectType(defect.defectType);
                                faultBuilder.Append($"{defectTypeName}(位置:{defect.x},{defect.y});");

                                Console.WriteLine($"{defect.x}  {defect.y}  类型: {defect.defectType}  {defectTypeName}");

                                // 保存缺陷点用于绘制
                                List<Point> points = GetPoints(defect.x, defect.y, defect.width, defect.height).ToList();
                                tempDefectPoints.Add(points);
                            }

                            result.Faults = faultBuilder.ToString();
                        }
                        else
                        {
                            result.isNG = false;
                            result.Faults = "OK";
                            Console.WriteLine("结果: $BlisterOK");
                        }

                        // 绘制缺陷框
                        if (tempDefectPoints.Count > 0)
                        {
                            displayBitmap = RectPoints1(new Bitmap(bitmap), tempDefectPoints);
                        }
                        else
                        {
                            displayBitmap = new Bitmap(bitmap);
                        }
                        try
                        {
                            string productId = ProductInfoManager.CurrentProductId;
                            string productName = ProductInfoManager.CurrentProductName;
                            switch (stationId)
                            {
                                case 1:
                                    CameraResult01 cameraResult1 = new CameraResult01();
                                    cameraResult1.DataTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                                    cameraResult1.Location = "工位1位置";
                                    cameraResult1.iWidth = bitmap.Width.ToString();
                                    cameraResult1.iHeight = bitmap.Height.ToString();
                                    cameraResult1.iName = "工位一";
                                    cameraResult1.isOkSave = true;
                                    cameraResult1.Faults = result.Faults;
                                    cameraResult1.isNG = result.isNG;
                                    BuilderManager.UpdateBuilderForCamera1(productId, productName, sampleId, cameraResult1);
                                    break;
                                case 2:
                                    CameraResult02 cameraResult2 = new CameraResult02();
                                    cameraResult2.DataTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                                    cameraResult2.Location = "工位2位置";
                                    cameraResult2.iWidth = bitmap.Width.ToString();
                                    cameraResult2.iHeight = bitmap.Height.ToString();
                                    cameraResult2.iName = "工位二";
                                    cameraResult2.isOkSave = true;
                                    cameraResult2.Faults = result.Faults;
                                    cameraResult2.isNG = result.isNG;
                                    BuilderManager.UpdateBuilderForCamera2(productId, productName, sampleId, cameraResult2);
                                    break;
                                case 3:
                                    CameraResult03 cameraResult3 = new CameraResult03();
                                    cameraResult3.DataTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                                    cameraResult3.Location = "工位3位置";
                                    cameraResult3.iWidth = bitmap.Width.ToString();
                                    cameraResult3.iHeight = bitmap.Height.ToString();
                                    cameraResult3.iName = "工位三";
                                    cameraResult3.isOkSave = true;
                                    cameraResult3.Faults = result.Faults;
                                    cameraResult3.isNG = result.isNG;
                                    BuilderManager.UpdateBuilderForCamera3(productId, productName, sampleId, cameraResult3);
                                    break;

                            }
                        }
                        catch
                        {
                            Console.WriteLine("存储失败");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"解析JSON错误: {ex.Message}\n{ex.StackTrace}");
                        result.Faults = "解析错误";
                        displayBitmap = CreateErrorBitmap(bitmap, $"解析错误: {ex.Message}");
                    }
                }
                else
                {
                    Console.WriteLine("推理失败: 返回空指针");
                    result.Faults = "推理错误";
                    displayBitmap = CreateErrorBitmap(bitmap, "推理错误");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"图像处理异常: {ex.Message}\n{ex.StackTrace}");
                result.Faults = $"处理异常: {ex.Message}";
                displayBitmap = CreateErrorBitmap(bitmap, $"处理异常: {ex.Message}");
            }
            finally
            {


                // 安全更新图像
                if (MainForm.main_Form != null)
                {
                    MainForm.main_Form.Invoke((MethodInvoker)delegate
                    {
                        var targetBox = MainForm.main_Form.pictureBoxes[stationId - 1];

                        if (targetBox.Image != null)
                        {
                            var oldImage = targetBox.Image;
                            targetBox.Image = null;
                            oldImage.Dispose();
                        }

                        if (displayBitmap != null)
                        {
                            targetBox.Image = new Bitmap(displayBitmap);
                        }
                        else
                        {
                            targetBox.Image = new Bitmap(bitmap);
                        }

                        targetBox.Refresh();
                    });

                    
                }

                // 释放资源
                if (displayBitmap != null)
                {
                    displayBitmap.Dispose();
                }
            }
        }

        // 创建错误信息图像的辅助方法
        private static Bitmap CreateErrorBitmap(Bitmap original, string message)
        {
            var bitmap = new Bitmap(original);
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.DrawString(message,
                    new Font("Arial", 12),
                    Brushes.Red,
                    new Point(10, 10));
            }
            return bitmap;
        }

        public static Bitmap RectPoints1(Bitmap source, List<List<Point>> points)
        {
            var result = new Bitmap(source.Width, source.Height, source.PixelFormat);

            using (var g = Graphics.FromImage(result))
            {
                // 高质量渲染配置
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                // 绘制原始图像
                g.DrawImage(source, 0, 0);

                // 使用绿色边框配置
                using (var pen = new Pen(Color.LimeGreen, 5) // 线宽改为2像素
                {
                    DashStyle = System.Drawing.Drawing2D.DashStyle.Solid 
                })
                using (var font = new Font("Arial", 10, FontStyle.Bold))
                {
                    foreach (var polygon in points)
                    {
                        if (polygon.Count >= 4)
                        {
                            g.DrawPolygon(pen, polygon.ToArray());

                            var labelPos = new Point(polygon[0].X + 5, polygon[0].Y - 20);
                            g.DrawString(" ", font, Brushes.LimeGreen, labelPos);
                        }
                    }
                }
            }

            return result;
        }
        public static Bitmap RectPoints2(Bitmap source, List<List<Point>> points, List<string> defectTypes)
        {
            // 创建结果位图
            var result = new Bitmap(source.Width, source.Height, source.PixelFormat);

            using (var g = Graphics.FromImage(result))
            {
                // 高质量渲染配置
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

                // 绘制原始图像
                g.DrawImage(source, 0, 0);

                // 使用绿色边框配置
                using (var pen = new Pen(Color.LimeGreen, 5))
                using (var font = new Font("Arial", 18, FontStyle.Bold))
                using (var textBrush = new SolidBrush(Color.LimeGreen))
                using (var backgroundBrush = new SolidBrush(Color.FromArgb(128, 0, 0, 0))) // 半透明黑色背景
                {
                    for (int i = 0; i < points.Count; i++)
                    {
                        var polygon = points[i];
                        if (polygon.Count < 4) continue;

                        // 绘制缺陷框
                        g.DrawPolygon(pen, polygon.ToArray());

                        // 获取当前缺陷类型
                        string defectType = i < defectTypes.Count ? defectTypes[i] : "未知缺陷";

                        // 计算文本位置（在第一个点附近）
                        Point labelPos = polygon[0];

                        // 计算文本尺寸
                        SizeF textSize = g.MeasureString(defectType, font);

                        // 创建文本背景矩形
                        RectangleF textRect = new RectangleF(
                            labelPos.X + 5,
                            labelPos.Y - textSize.Height - 5,
                            textSize.Width + 10,
                            textSize.Height + 5
                        );

                        // 绘制半透明背景
                        g.FillRectangle(backgroundBrush, textRect);

                        // 绘制缺陷类型文本
                        g.DrawString(
                            defectType,
                            font,
                            textBrush,
                            textRect.X + 5,
                            textRect.Y + 2
                        );
                    }
                }
            }

            return result;
        }
        public static Image RectPoints(Image bitmapInput)
        {
            //Bitmap bitmap = new Bitmap(Camera_Form.frameForSave.Image.ToBitmap());
            Bitmap bitmap = new Bitmap(bitmapInput);

            Graphics graphics1 = Graphics.FromImage(bitmap);

            Pen pen = new Pen(Color.Green, 5);
            foreach (var item in pointsList)
            {
                graphics1.DrawLines(pen, item.ToArray());
                graphics1.DrawLine(pen, item.ToArray()[0], item.ToArray()[3]);
            }

            bitmap.Save("out\\" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".bmp");

            graphics1.Dispose();

            return bitmap;
        }

        public static void RectPoints(IntPtr intPtr)
        {
            //Bitmap bitmap = new Bitmap(Camera_Form.frameForSave.Image.ToBitmap());
            //Bitmap bitmap = new Bitmap(bitmapInput);

            Graphics graphics1 = Graphics.FromHwnd(intPtr);

            Pen pen = new Pen(Color.Green, 5);
            foreach (var item in pointsList)
            {
                graphics1.DrawLines(pen, item.ToArray());
                graphics1.DrawLine(pen, item.ToArray()[0], item.ToArray()[3]);
            }

            //bitmap.Save("out\\" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".bmp");

            graphics1.Dispose();

            //return bitmap;
        }
        public static List<List<Point>> pointsList = new List<List<Point>>();

        public static Point[] GetPoints(int x,int y,int width,int height)
        {
            Point[] points = new Point[4];

            //points[0] = new Point(x, y);
            //points[1] = new Point(x + width, y);
            //points[2] = new Point(x + width, y - height);
            //points[3] = new Point(x, y - height);

            points[0] = new Point(x, y + height);
            points[1] = new Point(x + width, y + height); 
            points[2] = new Point(x + width, y);
            points[3] = new Point(x, y);

            return points;
        }
        public static Image RectPoints(Bitmap bitmap, List<List<Point>> pointsList)
        {
            //Console.WriteLine("bitmap.Size: "+bitmap.Size);
            //Bitmap bitmap = new Bitmap(bitmapInput);
            Bitmap convertedImage = new Bitmap(
            bitmap.Width,
            bitmap.Height,
            PixelFormat.Format32bppArgb);

            using (Graphics g = Graphics.FromImage(convertedImage))
            {
                g.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height);
            }

            Graphics graphics1 = Graphics.FromImage(convertedImage);

            Pen pen = new Pen(Color.Green, 5);

            //foreach (var item in pointsList.ToArray())
            //{
            //    graphics1.DrawLines(pen, item.ToArray());
            //    graphics1.DrawLine(pen, item.ToArray()[0], item.ToArray()[3]);
            //}
            for (int i = 0; i < pointsList.Count; i++)
            {
                graphics1.DrawLines(pen, pointsList[i].ToArray());
                graphics1.DrawLine(pen, pointsList[i].ToArray()[0], pointsList[i].ToArray()[3]);
            }

            graphics1.Dispose();
            return convertedImage;
        }
        //public static string GetDefectType(int defectType)
        //{
        //    DefectType defect = (DefectType)defectType;
        //    return defect.ToString();
        //}
        //public static HashSet<DefectType> SelectedDefectTypes = new HashSet<DefectType>();

        //// 添加缺陷过滤方法
        //public static List<DefectMessage> FilterDefects(List<DefectMessage> defects)
        //{
        //    return defects.Where(d => SelectedDefectTypes.Contains((DefectType)d.defectType)).ToList();
        //}
        public static HashSet<int> SelectedDefectTypes = new HashSet<int>();
        public static HashSet<int> SelectedDefectTypesTablet = new HashSet<int>();

        // 当前产品类型
        public static ProductType CurrentProductType = ProductType.Capsule;
        public static string CurrentEngine = "";
        // 修改过滤方法
        public static List<DefectMessage> FilterDefects(List<DefectMessage> defects)
        {
            if (CurrentProductType == ProductType.Capsule)
            {
                return defects.Where(d => SelectedDefectTypes.Contains(d.defectType)).ToList();
            }
            else
            {
                return defects.Where(d => SelectedDefectTypesTablet.Contains(d.defectType)).ToList();
            }
        }

        // 修改GetDefectType方法
        public static string GetDefectType(int defectType)
        {
            try
            {
                if (CurrentProductType == ProductType.Capsule)
                {
                    DefectType defect = (DefectType)defectType;
                    return defect.ToString();
                }
                else
                {
                    DefectType1 defect = (DefectType1)defectType;
                    return defect.ToString();
                }
            }
            catch
            {
                return "未知缺陷";
            }
        }
    }
}
